<template>
  <div style="display: flex; height: 100%;">
    <!-- 左侧岗位列表 -->
    <div style="width: 20%; border-right: 1px solid #eee; padding: 10px;">
      <el-menu :default-active="selectedPost" @select="handlePostSelect"
        style="border-right: none; background-color: transparent;" class="custom-menu">
        <el-menu-item v-for="post in uniquePosts" :key="post" :index="post">
          {{ post }}
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧表格和上传按钮 -->
    <div style="flex: 1; padding: 10px;">
      <!-- 上传按钮 -->
      <div style="display: flex; justify-content: flex-end; margin-bottom: 16px;">
        <el-button @click="uploadDialogVisible = true">上传简历</el-button>
      </div>

      <!-- 简历表格 -->
      <el-table :data="filteredTableData" style="width: 100%">
        <el-table-column prop="userid" label="用户ID" width="120" />
        <!-- <el-table-column prop="reid" label="简历岗位" /> -->
        <el-table-column prop="name" label="简历名称" />
        <!-- <el-table-column prop="scheme" label="方案" /> -->
        <!-- <el-table-column prop="content" label="简历链接" /> -->
        <el-table-column prop="notes" label="备注" />
        <el-table-column prop="todate" label="创建时间" />
        <el-table-column label="查看简历" width="120">
          <template #default="scope">
            <el-button type="text" class="JNPF-table-Btn" size="mini" @click="handleViewDetail(scope.row)">
              下载
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="解析/画像" width="120">
          <template #default="scope">
            <el-button size="mini" type="text" style="color: #000;" @click="handleViewAnalysis(scope.row)">
              解析/画像
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="删除简历" width="120">
          <template #default="scope">
            <el-button type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination background layout="prev, pager, next" :total="pagination.total" :page-size="pagination.pageSize"
        :current-page="pagination.page" @current-change="handlePageChange" style="margin-top: 16px;" />
    </div>

    <!-- 上传简历弹窗 -->
    <el-dialog title="上传简历" :visible.sync="uploadDialogVisible" width="520px">
      <el-form :model="uploadForm" label-width="120px">
        <!-- <el-form-item label="上传类型">
          <el-radio-group v-model="uploadForm.type">
            <el-radio label="overwrite">覆盖原有版本</el-radio>
            <el-radio label="new">仅上传</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- 选择已有简历进行覆盖 -->
        <!-- <el-form-item label="选择已有简历" v-if="uploadForm.type === 'overwrite'"> -->
        <!-- 第一级：选择岗位 -->
        <!-- <el-select v-model="uploadForm.selectedPost" placeholder="请选择岗位" style="margin-bottom: 12px; width: 100%;">
            <el-option v-for="post in uniquePosts" :key="post" :label="post" :value="post" />
          </el-select> -->

        <!-- 第二级：选择该岗位下的简历 -->
        <!-- <el-select v-model="uploadForm.selectedResumeId" placeholder="请选择简历" :disabled="!uploadForm.selectedPost">
            <el-option v-for="item in resumeListByPost" :key="item.reid" :label="item.name" :value="item.reid" />
          </el-select>
        </el-form-item> -->

        <!-- 新建简历名称 -->
        <el-form-item label="岗位" v-if="uploadForm.type === 'new'">
          <el-select v-model="uploadForm.selectedPost" filterable allow-create default-first-option
            placeholder="请选择或输入岗位">
            <el-option v-for="post in uniquePosts" :key="post" :label="post" :value="post" />
          </el-select>
        </el-form-item>

        <el-form-item label="简历名称" v-if="uploadForm.type === 'new'">
          <el-input v-model="uploadForm.name" placeholder="请输入简历名称" />
        </el-form-item>

        <el-form-item label="上传文件">
          <el-upload class="upload-resume" drag :show-file-list="true" :auto-upload="false"
            :on-change="handleFileChange" action="#">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">仅支持 PDF 或 DOC 文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="uploadForm.notes" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResume">确认上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getResumeList, createResume, updateResume } from '@/api/example/resume'
import OSS from 'ali-oss'
import request from '@/utils/request'
import axios from 'axios';

export default {
  name: 'ResumeList',
  data() {
    return {
      tableData: [],
      selectedPost: '',
      pagination: { page: 1, pageSize: 10, total: 0 },
      uploadDialogVisible: false,
      uploadForm: {
        type: 'new',
        selectedResumeId: '',
        selectedPost: '',
        name: '',
        notes: '',
        url: ''
      },
      uploadFile: null,
      base64FileContent: '',
      ossConfig: {
        region: 'oss-cn-wuhan-lr',
        accessKeyId: 'LTAI5tE1sjS9v6rVPid3HXzr',
        accessKeySecret: 'd3dCLmg0CBQgMX5fbSjZc6qMPWJcMj',
        bucket: 'mangopdf',
      },
      resumeData: null,
      resumePaint: null
    }
  },
  computed: {
    uniquePosts() {
      return [...new Set(this.tableData.map(item => item.reid))];
    },
    filteredTableData() {
      return this.selectedPost
        ? this.tableData.filter(item => item.reid === this.selectedPost)
        : [];
    },
    currentUser() {
      return this.$store.state.user.userInfo || {};
    },

    resumeListByPost() {
      return this.uploadForm.selectedPost
        ? this.tableData.filter(item => item.reid === this.uploadForm.selectedPost)
        : [];
    },
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      getResumeList({
        page: this.pagination.page,
        pageSize: this.pagination.pageSize
      }).then(res => {
        const data = res.data || {};
        this.tableData = Array.isArray(data.list) ? data.list : [];
        if (data.pagination) {
          this.pagination.total = data.pagination.total || 0;
          this.pagination.page = data.pagination.currentPage || 1;
          this.pagination.pageSize = data.pagination.pageSize || 10;
        }
        if (!this.selectedPost && this.uniquePosts.length > 0) {
          this.selectedPost = this.uniquePosts[0];
        }
      });
    },
    handlePostSelect(post) {
      this.selectedPost = post;
    },
    handlePageChange(page) {
      this.pagination.page = page;
      this.fetchData();
    },
    handleViewDetail(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在下载简历 PDF...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const resumeUrl = row.content;
        window.open(resumeUrl, '_blank')
      } catch (error) {
        this.$message.error('下载简历失败');
      } finally {
        loading.close();
      }
    },
    handleViewAnalysis(row) {
      console.log("1", row.analysis)
      if (row.analysis) {
        const analysisData = JSON.parse(row.analysis);
        console.log("2", analysisData)
        const paintData = row.paint ? JSON.parse(row.paint) : null;
        this.$emit('view-analysis', { analysis: analysisData, paint: paintData });
        //将router转到另一个页签，然后把这两个数据传给那个页签文件中的resumeData和resumePaint
        this.$parent.showResumeAnalysis(analysisData, paintData);
        // this.$router.push({
        //   path: '/profile/analysis',
        //   query: {
        //     analysis: JSON.stringify(analysisData),
        //     paint: paintData ? JSON.stringify(paintData) : null
        //   }
        // });

      } else {
        this.$message.warning('该简历暂无解析数据');
      }
    },
    handleFileChange(file) {
      console.log('选择的文件:', file);

      if (!file.raw) {
        this.uploadFile = null;
        console.log('选择的文件无效:', file);
        return;
      }

      const allowedTypes = [
        "application/msword",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/pdf",
      ];

      if (!allowedTypes.includes(file.raw.type)) {
        this.error = "请上传.doc、.docx或.pdf格式的简历文件";
        this.uploadFile = null;
        return;
      }
      this.uploadFile = file.raw ? file.raw : file;
      console.log('上传的文件对象:', this.uploadFile);
      const reader = new FileReader();
      reader.onload = () => {
        const base64String = reader.result.split(",")[1];
        this.base64FileContent = base64String;
        console.log('文件blob内容:', this.base64FileContent);
      };
      reader.readAsDataURL(this.uploadFile);
      reader.onerror = () => {
        this.error = "读取文件失败";
        this.uploadFile = null;
      };


    },
    async submitResume() {
      console.log('提交的表单数据:', this.uploadForm);

      // 确保文件已选择，并且 base64 已生成
      if (!this.uploadFile) {
        this.error = "请先选择简历文件";
        console.log('选择的文件无效:', this.uploadFile);
        return;
      }

      // 如果 base64 还没生成，需要先读取
      if (!this.base64FileContent) {
        try {
          this.base64FileContent = await new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result.split(",")[1]);
            reader.onerror = reject;
            reader.readAsDataURL(this.uploadFile);
          });
        } catch (err) {
          this.error = "读取文件失败";
          console.error(err);
          return;
        }
      }

      this.loading = true;
      this.error = "";

      const url_parser = "https://resumesdk.market.alicloudapi.com/ResumeParser";
      const url_profiler = "https://aliprofile.market.alicloudapi.com/ResumeProfiler";
      const appcode = "c69a92a5c3bd446bab58229251f622de";

      const data = {
        file_name: this.uploadFile.name,
        file_cont: this.base64FileContent,
        need_avatar: 1,
      };

      try {
        console.log("准备发送请求:", data, "headers:", {
          Authorization: "APPCODE " + appcode,
          "Content-Type": "application/json; charset=UTF-8"
        });
        const response_parser = await axios.post(url_parser, data, {
          headers: {
            Authorization: "APPCODE " + appcode,
            "Content-Type": "application/json; charset=UTF-8",
          },
        });

        const response_profiler = await axios.post(url_profiler, data, {
          headers: {
            Authorization: "APPCODE " + appcode,
            "Content-Type": "application/json; charset=UTF-8",
          },
        });

        if (response_parser.status === 200) {
          this.resumeData = response_parser.data;
          this.$message.success("简历解析成功！");
          console.log("解析后的简历数据:", this.resumeData);
        } else {
          this.error = `请求失败，状态码：${response_parser.status}`;
        }

        if (response_profiler.status === 200) {
          this.resumePaint = response_profiler.data;
          // this.uploadFile = null;
          this.$message.success("简历画像成功！");
          console.log("解析后的简历画像数据:", this.resumePaint);
        } else {
          this.error = `请求失败，状态码：${response_profiler.status}`;
        }

      } catch (err) {
        if (err.response && err.response.data) {
          this.error = "请求错误：" + JSON.stringify(err.response.data);
        } else {
          this.error = "请求错误：" + err.message;
        }
      } finally {
        this.loading = false;
      }
      // 上传简历文件至 OSS
      this.uploadToOSS(this.uploadFile)
        .then(url => {
          console.log('1上传成功，文件地址：', url);
          this.uploadForm.url = url;

          // 上传简历解析结果以及 url 到数据库
          this.handleAdd();

          // 关闭弹窗
          this.uploadDialogVisible = false;
        })
        .catch(err => {
          console.error('OSS上传失败：', err);
        });
    },





    // async uploadToOSS(blob) {
    //   const client = new OSS(this.ossConfig);
    //   const fileName = `interview-reports/${this.currentUser.id || 'anonymous'}/${Date.now()}.pdf`;
    //   const result = await client.put(fileName, blob, {
    //     headers: {
    //       'Content-Type': this.uploadForm.file.type,
    //       'Content-Disposition': `inline`
    //     }
    //   });
    //   return result.url;
    // },
    async uploadToOSS(file) {
      const client = new OSS(this.ossConfig);
      const uploadFileName = file ? file.name : 'moren';
      const fileName = `interview-reports/${this.currentUser.id || 'anonymous'}/${Date.now()}-${uploadFileName}`;
      const result = await client.put(fileName, file, {
        headers: {
          'Content-Type': file.type,
          'Content-Disposition': 'inline'
        }
      });
      console.log('上传成功，文件地址：', result.url);
      return result.url;
    },

    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        console.log('删除 ID:', id);
        request({
          url: `/api/example/Whu_resume/${id}`,
          method: 'DELETE'
        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            onClose: () => {
              this.fetchData()
            }
          });
        })
      }).catch(() => {
      });
    },
    handleAdd() {
      {
        console.log('添加简历');
        request({
          url: `/api/example/Whu_resume`,
          method: 'POST',
          data: {
            name: this.uploadForm.name || '默认名称',
            reid: this.uploadForm.selectedPost || '默认岗位',
            content: this.uploadForm.url || '默认内容',
            notes: this.uploadForm.notes || '无备注',
            scheme: this.uploadForm.scheme || '默认方案',
            todate: new Date().toISOString(),
            analysis: JSON.stringify(this.resumeData || {}),
            paint: JSON.stringify(this.resumePaint || {})
          }

        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            onClose: () => {
              this.fetchData()
            }
          });
        })
      }
    }
  }
}
</script>

<style scoped>
.upload-resume {
  width: 100%;

}

/* 所有文字默认黑色 */
.custom-menu .el-menu-item {
  color: #554a2f !important;
  font-size: 14px;
  height: 60px !important;
  /* 调高菜单项高度 */
  line-height: 60px !important;
  /* 文字垂直居中 */
  transition: font-size 0.2s ease, background-color 0.3s ease;
}


/* 鼠标悬停时字体变大 */
.custom-menu .el-menu-item:hover {
  font-size: 16px;
  background-color: transparent !important;
}

/* 选中状态背景淡黄色，文字依然黑色 */
.custom-menu .el-menu-item.is-active {
  background-color: #f0e6d2 !important;
  /* 淡黄色 */
  color: #635637 !important;
  /* border: #c6ab6d 1px solid; */
  border-radius: 10px;
}
</style>
